import { defineStore } from 'pinia';
import { ref,computed } from 'vue';
export const useCartStore = defineStore('cart',()=>{
	persist: true // 启用持久化
	const cartList = ref(uni.getStorageSync('cartList')||[])
	// 计算商品的总数量
	const total = computed(()=>{
		return cartList.value.reduce((total,item)=>total+=item.goods_count,0)
	})
	// 加入购物车
	const addToCart = (goods) =>{
		const findResult = cartList.value.find(x=>x.goods_id===goods.goods_id)
		if(!findResult){
			cartList.value.push(goods)
			
		}else{
			findResult.goods_count++
		}
		saveToStorage()
	}
	// 保存到本地
	const saveToStorage = () =>{
		uni.setStorageSync('cartList',cartList.value)
	}
	// 更新购物车商品状态
	const updateGoodsState = (goods) => {
		const findResult = cartList.value.find(x => x.goods_id === goods.goods_id)
		if (findResult) {
		    // 更新对应商品的勾选状态
		    findResult.goods_state = goods.goods_state
		    // 持久化存储到本地
		    saveToStorage()
		 }
	}
	// 更新购物车商品的数量
	const updateGoodsCount = (goods) => {
		const findResult = cartList.value.find(x=>x.goods_id === goods.goods_id)
		if(findResult){
			findResult.goods_count = goods.goods_count
			saveToStorage()
		}
	}
	//删除购物车商品
	const removeGoodsById = (goods_id) => {
		cartList.value=cartList.value.filter(x=>x.goods_id !== goods_id)
		saveToStorage()
	}
	//计算勾选商品的数量
	const checkedCount = computed(()=>{
		return cartList.value.filter(x=>x.goods_state).reduce((total,item)=>total+=item.goods_count,0)
	})
	//全选按钮
	const updateAllGoodsState = (checked) => {
		cartList.value.forEach(item=>item.goods_state = checked)
		saveToStorage()
	}
	//计算勾选商品的价格
	const checkedGoodsAmount = computed(()=>{
		return cartList.value.filter(x=>x.goods_state).reduce((total,item)=>total+=item.goods_count*item.goods_price,0).toFixed(2)
	}) 
	return{
		cartList,
		total,
		addToCart,
		saveToStorage,
		updateGoodsState,
		updateGoodsCount,
		removeGoodsById,
		checkedCount,
		updateAllGoodsState,
		checkedGoodsAmount
	}
})